<?php

namespace App\Http\Controllers;

use App\Models\Deposit;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kuyuan\Phpwidget\Str;

class DepositController extends Controller
{
    /**
     * 当前用户提现列表
     */
    public function index(Request $request)
    {
        $_limit = $request->input('limit', [0, 10]);
        $Deposit = Deposit::where("member_id", auth('member')->id())
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderBy("id", "desc")
            ->get();
        if ($Deposit) {
            foreach ($Deposit as $item) {
                $item->setAppends(['time']);
                $item->money = Str::format_money($item->money);
            }
        }
        return response(['data' => $Deposit]);
    }

    /**
     * 提现
     */
    public function store()
    {
        DB::beginTransaction();
        try {
            // 提现至目标 account = 系统账户余额 wx = 微信钱包
            $_target = 'account';
            $_member_id = auth('member')->id();
            $_deposit_money = Member::where("id", $_member_id)->lockForUpdate()->value('red_balance');

            // 验证用户余额
            if ($_deposit_money <= 0) {
                throw new \PDOException("余额不足", 402);
            }


            // 最低提现金额验证
            $Setting = $this->getConfig();
            if ($_deposit_money < $Setting->finance->low_deposit) {
                throw new \PDOException('提现金额不能低于' . Str::format_money($Setting->finance->low_deposit) . '元', 402);
            }

            // 减去用户红包余额
            Member::where('id', $_member_id)->decrement('red_balance', $_deposit_money);

            // 创建提现记录
            $Deposit = new Deposit();
            $Deposit->order_id = $this->createOrderId();
            $Deposit->member_id = $_member_id;
            $Deposit->money = $_deposit_money;
            $Deposit->save();

            // 判断是否直接到用户微信钱包
            if ($Setting->finance->deposit_check > 0 && $_deposit_money < $Setting->finance->deposit_check) {
                $_to_balance_result = $this->toBalance(
                    $_deposit_money,
                    'deposit',
                    $Deposit->id,
                    $_member_id,
                    '红包提现'
                );
                if ($_to_balance_result['code'] == 200) {
                    $Deposit->status = 1;
                    $Deposit->save();
                    $_target = 'wx';
                }
            }
            DB::commit();
            return response(['data' => $_target]);
        } catch (\PDOException $e) {
            DB::rollBack();
            return response(['message' => $e->getMessage()], $e->getCode());
        }
    }

    /**
     * 创建订单id
     */
    private function createOrderId()
    {
        $_order_id = '' . time() . mt_rand(10000, 99999);
        if (Deposit::where('order_id', $_order_id)->exists()) {
            return $this->createOrderId();
        }
        return $_order_id;
    }

    /**
     * 用户可提现余额
     */
    public function money()
    {
        return response([
            'data' => Str::format_money(Member::where('id', auth('member')->id())->value('red_balance'))
        ]);
    }

    // ------------------------------------------------

    /**
     * 提现数据总数
     */
    public function total(Request $request)
    {
        $_status = $request->input('status', 0);
        $_count = Deposit::where("status", $_status)->count();
        return response(["data" => $_count]);
    }

    /**
     * 提现数据列表
     */
    public function getList(Request $request)
    {
        $_status = $request->input('status',0);
        $_limit = $request->input('limit', [0,10]);
        $Deposit = Deposit::where("status",$_status)
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderBy('id','desc')
            ->get();
        if($Deposit) {
            foreach($Deposit as $item) {
                $item->setAppends(['time']);
                $item->member;
                $item->money = Str::format_money($item->money);
            }
        }
        return response(['data'=>$Deposit]);
    }

    /**
     * 提现
     */
    public function deposit($_id)
    {
        DB::beginTransaction();
        try{
            $Deposit = Deposit::lockForUpdate()->find($_id);
            if(!$Deposit || $Deposit->status != 0) {
                throw new \PDOException('非法请求',402);
            }
            $_deposit_result = $this->toBalance($Deposit->money,'deposit',$_id,$Deposit->member_id,'红包提现');
            if($_deposit_result['code'] != 200) {
                throw new \PDOException($_deposit_result['message'],402);
            }
            $Deposit->status = 1;
            $Deposit->save();
            DB::commit();
            return response(['data'=>'success']);
        }catch (\PDOException $e) {
            DB::rollBack();
            return response(['message'=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     * 拒绝一条申请提现
     * @param $_id
     * @return mixed
     */
    public function refuse($_id)
    {
        DB::beginTransaction();
        try{
            $Deposit = Deposit::lockForUpdate()->find($_id);
            if(!$Deposit || $Deposit->status != 0) {
                throw new \PDOException('非法操作',402);
            }
            $Deposit->status = 2;
            $Deposit->save();
            DB::commit();
            return response(['data'=>'success']);
        }catch (\PDOException $e) {
            DB::rollBack();
            return response(['message'=>$e->getMessage()],$e->getCode());
        }
    }
}
